﻿using Aliyun.OSS;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using System.Security.AccessControl;

namespace Api.Ali
{
    /// <summary>
    /// 阿里云OSS
    /// </summary>
    public class Oss : ISingleton
    {
        #region 配置信息
        /// <summary>
        /// 
        /// </summary>
        public string baseUrl { get { return App.Configuration.GetSection("aliyun:baseUrl").Value ?? ""; } }

        /// <summary>
        /// 
        /// </summary>
        public string endpoint { get { return App.Configuration.GetSection("aliyun:endpoint").Value ?? ""; } }

        /// <summary>
        /// 
        /// </summary>
        public string accessKeyId { get { return App.Configuration.GetSection("aliyun:key").Value ?? ""; } }

        /// <summary>
        /// 
        /// </summary>
        public string accessKeySecret { get { return App.Configuration.GetSection("aliyun:secret").Value ?? ""; } }

        private string bucketName = "bapings";
        #endregion

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="file"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string Upload(string dir, Stream file, string fileName)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                string fileExt = Path.GetExtension(fileName);

                fileName = $"{Guid.NewGuid().ToString()}{fileExt}";

                string fileUrl = $"{dir}/{fileName}";

                var result = client.PutObject(bucketName, fileUrl, file);

                return $"https://{baseUrl}/{fileUrl}";
            }
            catch (Exception e)
            {
                throw Oops.Oh(e.Message);
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] Download(string url)
        {

            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            string objName = url.Replace("https://" + baseUrl + "/", "");

            var request = new GetObjectRequest(bucketName, objName);

            var obj = client.GetObject(request);

            using (MemoryStream ms = new MemoryStream())
            {
                obj.Content.CopyTo(ms);

                return ms.ToArray();
            }
        }
    }
}
